<template>
  <div class="goodsEdit">
    <div v-if="accountStatus == 0">
      <!-- <h1 class="mb-3">{{ id ? "编辑" : "新建" }}商品</h1> -->
      <el-form label-width="110px" :model="form" :rules="rules" ref="form">
        <el-form-item label="标题" prop="name" class="w50">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="背景图" class="img-list" prop="image">
          <el-radio-group v-model="form.image">
            <el-radio :label="item.image_url" border v-for="item in bgImgList" :key="item.image_url">
              <img :src="item.image_url" />
              <div class="title center fs16">{{ item.image_name }}</div>
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- <el-form-item label="主图" prop="img" class="img-wrapper">
        <el-upload
          class="avatar-uploader"
          action="http://dev-cloud-admin.siyuyunai.com/mallAdmin/upload?files"
          :data="uploadData"
          :headers="getAuthHeaders()"
          :show-file-list="false"
          :on-success="uploadSuccess"
          :before-upload="beforeUpload"
        >
          <img v-if="image" :src="image" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item> -->
        <el-form-item label="商品所属类别" prop="cate_id" class="w50">
          <el-cascader
            ref="cascaderCate"
            v-model="form.cate_id"
            :options="cateList"
            clearable
            :props="{ expandTrigger: 'hover' }"
            @change="handleChange"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="描述" prop="description" class="w90">
          <Tinymce ref="editor" v-model="form.description" :height="200" />
        </el-form-item>
        <el-form-item label="下单方式" prop="order_method" style="margin-bottom: 5px;">
          <el-checkbox-group v-model="form.order_method">
            <el-checkbox :label="item" name="order_method" v-for="(item, i) in orderMethodList" :key="i"></el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="已选择">
          <div>{{ form.order_method }}</div>
          <div>按顺序选择，如果顺序不对，可以重新选择</div>
        </el-form-item>
        <el-form-item label="价格" style="width:400px">
          <el-input-number size="medium" :precision="2" controls-position="right" v-model="form.price" :min="0.01">
            <template slot="append">元 / 个</template>
          </el-input-number>
          <span class="ml-2">元 / 个</span>
        </el-form-item>
        <el-form-item label="默认下单数量" style="width:300px">
          <el-input-number
            size="medium"
            controls-position="right"
            :precision="0"
            v-model="form.default_num"
            :min="1"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="商品状态">
          <el-radio v-model="form.on_shelf" label="1">正常</el-radio>
          <el-radio v-model="form.on_shelf" label="0">下架</el-radio>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="save('form')">保存</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="fs18 bold" v-else>此账号因多次违规，新建和编辑商品功能暂时不可用，请联系管理员处理</div>
  </div>
</template>

<script>
import GetCateList from "@/utils/productCate";
import Tinymce from "@/components/Tinymce";
import lf from "localforage";
export default {
  props: ["id"],
  components: {
    Tinymce,
  },
  data() {
    return {
      accountStatus: this.$store.state.accountStatus, // 账号状态 0 正常， 1 禁用
      image: "",
      uploadData: {},
      value: [],
      cateList: [
        // {
        //   value: "notes",
        //   label: "音符业务",
        //   children: [
        //     { value: "notesOnList", label: "音符上榜业务" },
        //     { value: "notesCancelOnList", label: "音符不上榜业务" },
        //     { value: "notesFans", label: "音符粉丝业务" },
        //     { value: "notesLike", label: "音符点赞业务" },
        //   ],
        // },
      ],
      bgImgList: [
        // { image_name: "", image_url: "" },
      ],
      orderMethodList: [],
      form: {
        name: "",
        image: "",
        cate_id: "",
        cateLabel: "",
        description: "",
        order_method: [],
        price: 0,
        default_num: 10,
        on_shelf: "1",
      },
      rules: {
        name: [
          { required: true, message: "请输入标题", trigger: "blur" },
          { min: 2, max: 30, message: "长度在 2 到 30 个字符", trigger: "blur" },
        ],
        image: [{ required: true, message: "请选择背景图片", trigger: "blur" }],
        cate_id: [{ required: true, message: "请选择商品所属类别", trigger: "change" }],
        order_method: [{ type: "array", required: true, message: "请至少选择一个下单方式", trigger: "change" }],
        description: [{ required: true, message: "请填写商品描述", trigger: "blur" }],
      },
    };
  },
  beforeCreate() {
    // 激活富文本编辑
    this.$store.commit("ActiveEditor");
  },
  created() {
    if (this.accountStatus != 0) return;
    this.$store.commit("changeBreadcrumb", this.$route);
    this.getAccount();
    this.getBgImgList();
    this.getCateList();
    this.findDictList();
    this.id && this.fetch();
  },
  updated() {},
  methods: {
    async getAccount() {
      const { data: res } = await this.$http.post("findSelfInfo");
      // console.log(res, "账号信息");
      if (res.code != "0") return this.$message("获取账号信息失败！");
      this.$store.commit("editAccountStatus", res.data);
      this.accountStatus = res.data.status;
    },
    uploadSuccess(res, file) {
      this.form.image = res.data;
      this.image = this.showImgUrl + res.data;
      // console.log(this.form.image, "图片id");
    },
    beforeUpload(file) {
      this.uploadData.files = file;
      // console.log(file.size);
      const isLt2M = file.size / 1024 / 1024 < 0.5;
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 0.5MB!");
      }
      return isLt2M;
    },
    // 获取背景图列表
    async getBgImgList() {
      const { data: res } = await this.$http.post("findProductImageByPage");
      // console.log(res, "获取图片返回的数据");
      if (res.code != "0") return this.$message("获取背景图片失败");
      this.bgImgList = [];
      res.data.forEach((item) => {
        const { image_name, image_url } = item;
        this.bgImgList.unshift({ image_name, image_url });
      });
    },
    // 获取下单方式列表
    async findDictList() {
      const { data: res } = await this.$http.post("findDictList");
      if (res.code != "0") return this.$message("获取信息失败！");
      this.orderMethodList = [];
      res.data.forEach((item) => {
        if (item.dict_name == "ORDER_METHOD") {
          this.orderMethodList.push(item.dict_lable);
        }
      });
      // console.log(this.orderMethodList, "下单方式");
    },
    // 获取商品分类列表
    async getCateList() {
      this.cateList = await GetCateList();
    },

    handleChange(value) {
      // console.log(this.form.cate_id, "类别");
      // console.log(value, "选中的分类值");
      const labelList = [];
      const checkedLabels = this.$refs["cascaderCate"].getCheckedNodes();

      checkedLabels.forEach(function(item) {
        if (!item.hasChildren) {
          labelList.push(item.label);
        }
      });
      // this.form.cateLabel = value.join(",");
      this.form.cateLabel = labelList.join(",");
      // this.form.cateValue = labelList;
      // console.log(this.form.cateLabel);
    },
    async save() {
      await this.getAccount();
      if (this.accountStatus != 0) return;
      this.$refs.form.validate(async (valid) => {
        if (!valid) return;
        let opt = Object.assign({}, this.form);
        // console.log(opt, "待传的参数对象");
        let cateID = Array.isArray(opt.cate_id) ? opt.cate_id[opt.cate_id.length - 1] : opt.cate_id;
        // console.log(cateID, " cateID");
        let order_method = [];
        opt.order_method.forEach((item) => {
          const obj = {};
          obj.name = item;
          obj.value = "";
          order_method.push(obj);
        });
        opt.order_method = JSON.stringify(order_method);
        // console.log(opt.order_method, " 下单方式json字符串");
        // console.log("category_id: " + cateID);
        const formData = new FormData();
        formData.append("member_id", this.$store.state.uid);
        formData.append("name", opt.name);
        formData.append("image", opt.image);
        formData.append("category_id", cateID);
        formData.append("description", opt.description);
        formData.append("order_method", opt.order_method);
        formData.append("price", opt.price);
        formData.append("default_num", opt.default_num);
        formData.append("on_shelf", opt.on_shelf);
        let res;
        if (this.id) {
          formData.append("id", this.id);
          res = await this.$http.post("editProduct", formData);
        } else {
          res = await this.$http.post("saveProduct", formData);
        }

        // console.log(res.data, "成功前的数据");
        if (res.data.code != "0") return this.$message("保存失败");
        // console.log(res.data, "保存成功");
        this.$message.success("保存成功");
        this.$router.push("/product/list");
      });
    },
    async fetch() {
      const currentGoods = await lf.getItem("currentGoods");
      currentGoods.order_method = JSON.parse(currentGoods.order_method);
      currentGoods.order_method.forEach((item, i, arr) => {
        arr[i] = item.name;
      });

      currentGoods.on_shelf = String(currentGoods.on_shelf);
      currentGoods.cate_id = currentGoods.category_id == 0 ? "" : currentGoods.category_id;
      // console.log(currentGoods, "接收的数据");
      this.form = currentGoods;
    },
  },
};
</script>

<style lang="scss">
.goodsEdit {
  padding-bottom: 50px;
  .el-cascader-menu__wrap {
    height: 180px !important;
  }
  .img-list {
    .el-radio.is-bordered {
      position: relative;
      padding: 12px 0px 0 12px;
      border-width: 2px;
      height: 205px;
    }
    .el-radio.is-bordered.is-checked {
      .title {
        color: #409eff;
      }
    }
    .title {
      top: 93%;
    }
    img {
      width: 100px;
      height: 157px;
      margin-right: 40px;
    }
  }
  .img-wrapper {
    .el-form-item__content {
      line-height: 0;
    }
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    height: auto;
    width: 100%;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
  }
}
</style>
